package UI;

import Service.AllOperating;
import Service.GetOriginalInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.bcel.internal.generic.NEW;
import controller.AnalysisResult;
import controller.GetWebMsgInterface;
import controller.impl.AnalysisResultImpl;
import controller.impl.GetWebMsg;
import encryption.DateController;
import model.JsonResult;
import model.NewRegular;
import model.Yangzhou;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
import java.util.Timer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainUI {

    private static final int DISCONNECT = 0;
    private static final int CONNECTING = 1;
    private static final int CONNECTED = 2;

    private static final int ONCE_COUNTS = 50;

    private final String title = "扬州";
    private int success = 0;
    private int fail = 0;

    private JFrame frame = new JFrame(title);
    private JLabel connStatus;
    private JLabel successTimes;
    private JLabel failTimes;
    private JLabel regularDailyUpdate;
    private JLabel regularUpdateMsg;
    private JLabel regularSelectMsg;
    private JButton connect;

    private Timer forGetInfo;
    private Timer forRegularUpdate;
    private AllOperating allOperating = new GetOriginalInfo();
    private GetWebMsgInterface getWebMsgInterface = new GetWebMsg();
    private AnalysisResult analysisResult = new AnalysisResultImpl();

    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
        mainUI.StartUI();
    }

    private void StartUI() {

        final String exitString = "退出";
        final int[] connectStatus = {DISCONNECT};
        JPanel panel = new JPanel();

        frame.add(panel);
        //关闭程序时停止运行
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 400, 300);
        frame.setLayout(null);

        connStatus = new JLabel("数据库连接状态：" + getConnectStatus(connectStatus[0]), JLabel.CENTER);
        connStatus.setBounds(100, 0, 200, 50);
        frame.add(connStatus);

        JButton exit = new JButton(exitString);
        exit.setBounds(150, 230, 100, 20);
        exit.addActionListener(new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        frame.add(exit);

        successTimes = new JLabel("成功转换：" + success + "条");
        successTimes.setBounds(150, 80, 100, 20);
        frame.add(successTimes);

        failTimes = new JLabel("转换失败：" + fail + "条");
        failTimes.setBounds(150, 110, 100, 20);
        frame.add(failTimes);

        regularDailyUpdate = new JLabel("每日更新:" + getConnectStatus(connectStatus[0]));
        regularDailyUpdate.setBounds(150, 140, 100, 20);
        frame.add(regularDailyUpdate);

        regularUpdateMsg = new JLabel("自动更新未开始");
        regularUpdateMsg.setBounds(150, 170, 300, 20);
        frame.add(regularUpdateMsg);

        regularSelectMsg = new JLabel("");
        regularSelectMsg.setBounds(150, 200, 200, 20);
        frame.add(regularSelectMsg);

        DateChooser mp = new DateChooser("yyyy-MM-dd", this);
        mp.setBounds(50, 200, 100, 20);
        frame.add(mp);

        connect = new JButton(getConnectString(connectStatus[0]));
        connect.setBounds(150, 50, 100, 20);
        connect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (connectStatus[0] == DISCONNECT) {
                    System.out.println("点击了连接");
                    connectStatus[0] = CONNECTING;
                    connect.setText(getConnectString(connectStatus[0]));
                    connStatus.setText("数据库连接状态：" + getConnectStatus(connectStatus[0]));
                    regularDailyUpdate.setText("每日更新:" + getConnectStatus(connectStatus[0]));

                    if (allOperating.testConnecting()) {
                        System.out.println("连接成功");
                        connectStatus[0] = CONNECTED;
                        connect.setText(getConnectString(connectStatus[0]));
                        connStatus.setText("数据库连接状态：" + getConnectStatus(connectStatus[0]));
                        regularDailyUpdate.setText("每日更新:" + getConnectStatus(connectStatus[0]));
                        regularUpdateMsg.setText("自动更新已开始");

                        forGetInfo = new Timer();
                        forGetInfo.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                System.out.println("开始获取数据");
                                getInfo();
                            }
                        }, 3000, 2000);

                        forRegularUpdate = new Timer();
                        forRegularUpdate.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                System.out.println("开始日常更新数据");
                                getRegularUpdate();
                            }
                        }, DateController.getTime());
                    }

                } else if (connectStatus[0] == CONNECTED) {
                    System.out.println("点击了断开");
                    connectStatus[0] = DISCONNECT;
                    connect.setText(getConnectString(connectStatus[0]));
                    connStatus.setText("数据库连接状态：" + getConnectStatus(connectStatus[0]));
                    regularDailyUpdate.setText("每日更新:" + getConnectStatus(connectStatus[0]));

                    forGetInfo.cancel();
                }
            }
        });
        frame.add(connect);

        frame.setVisible(true);
    }

    private void getRegularUpdate() {
        System.out.println("执行刷新数据");
        final String date = DateController.returnDate(DateController.getDayBefore(new Date()));
        final Yangzhou yangzhou = new Yangzhou("", date, "", "");

        //新线程执行更新操作
        new Thread(new Runnable() {
            public void run() {
                UpdateRegularMsg(yangzhou);
            }
        }).start();
    }

    public void UpdateRegularMsg(Yangzhou yangzhou) {
        String resultJson = null;
        resultJson = getWebMsgInterface.getJson2StringMsg(yangzhou);
        System.out.println(resultJson);
        if ("".equals(resultJson) || resultJson == null) {
            regularUpdateMsg.setText("网络连接失败");
            regularSelectMsg.setText("网络连接失败");
            return;
        }

        String date = yangzhou.getDate();

        Gson gson = new Gson();
        JsonResult<NewRegular> jsonResult = gson.fromJson(resultJson, new TypeToken<JsonResult<NewRegular>>() {
        }.getType());
        List<NewRegular> newRegulars = jsonResult.getResult();

        for (NewRegular regular : newRegulars) {
            StringBuffer sb = new StringBuffer();
            sb.append(regular.getSj().substring(0, 2));
            sb.append(":");
            sb.append(regular.getSj().substring(2));
            regular.setSj(sb.toString());
        }

        System.out.println(newRegulars.size());

        if (newRegulars.size() == 0) {
            regularUpdateMsg.setText(date + "无数据");
            regularSelectMsg.setText(date + "无数据");
            return;
        }

        int index = newRegulars.size();

        int time = 1;
        while (index > ONCE_COUNTS) {
            doUpdate(time, newRegulars, date, 1);
            index -= ONCE_COUNTS;
            ++time;
        }

        doUpdate(time, newRegulars, date, 2);

        regularUpdateMsg.setText(date + "已更新" + newRegulars.size() + "条数据");
        regularSelectMsg.setText(date + "已更新");
    }

    private void doUpdate(int time, List<NewRegular> newRegulars, String date, int type) {
        List<NewRegular> newRegularsForInsert = new LinkedList<NewRegular>();
        int maxNumber = 0;
        if (type == 1) {
            maxNumber = time * ONCE_COUNTS;
        } else if (type == 2) {
            maxNumber = newRegulars.size();
        }
        for (int i = (time - 1) * ONCE_COUNTS; i < maxNumber; i++) {
            newRegulars.get(i).setDate(date);
            newRegularsForInsert.add(newRegulars.get(i));
        }
        try {
            allOperating.insertDailyMsg(newRegularsForInsert);
        } catch (Exception e) {
            System.out.println("出错了");
        }
    }

    private void getInfo() {
        System.out.println("执行获取数据");
        List<Yangzhou> list = new ArrayList<Yangzhou>();
        list = new GetOriginalInfo().getAll();

        if (list.size() != 0) {
            for (final Yangzhou yangzhou : list) {
                new Thread(new Runnable() {
                    public void run() {
                        getRealMsg(yangzhou);
                    }
                }).start();
            }
        }
    }

    /**
     * 1.获取数据
     * 先获取到json数据 然后进行判断是否获取成功
     * 进行插入操作
     *
     * @param yangzhou
     */
    public void getRealMsg(Yangzhou yangzhou) {

        if (!isInputMsgError(yangzhou)) {
            //获取失败的操作
            System.out.println("error 3");
            yangzhou.setSendstatus("2");
            yangzhou.setReturnmsg("获取失败：error 3");
            addfail(yangzhou);
        }

        String resultJson = null;
        resultJson = getWebMsgInterface.getJson2StringMsg(yangzhou);
        if (resultJson != null && !("").equals(resultJson)) {
            System.out.println(resultJson);
            if (analysisResult.isGetMsgSuccess(resultJson)) {
                String resultmsg = analysisResult.getResultMsg(resultJson);
                System.out.println(resultmsg);
                yangzhou.setSendstatus("1");
                yangzhou.setReturnmsg(resultmsg);
                addsuccess(yangzhou);
            } else {
                //获取失败的操作
                System.out.println("error 1");
                yangzhou.setSendstatus("2");
                yangzhou.setReturnmsg("获取失败：error 1");
                addfail(yangzhou);
            }
        } else {
            //获取失败的操作
            System.out.println("error 2");
            yangzhou.setSendstatus("2");
            yangzhou.setReturnmsg("获取失败：error 2");
            addfail(yangzhou);
        }
    }

    private void addsuccess(Yangzhou yangzhou) {
        success++;
        successTimes.setText("成功转换数据" + success + "条");
        allOperating.update(yangzhou);
    }

    private void addfail(Yangzhou yangzhou) {
        fail++;
        failTimes.setText("转换失败：" + fail + "条");
        allOperating.update(yangzhou);
    }

    private String getConnectStatus(int connectStatus) {
        String status = "";
        switch (connectStatus) {
            case DISCONNECT:
                status = "未连接";
                break;

            case CONNECTING:
                status = "连接中...";
                break;

            case CONNECTED:
                status = "已连接";
                break;
        }
        return status;
    }

    private String getConnectString(int connectStatus) {
        String connect = "";
        switch (connectStatus) {
            case DISCONNECT:
                connect = "连接";
                break;

            case CONNECTING:
                connect = "连接中...";
                break;

            case CONNECTED:
                connect = "中止";
                break;
        }
        return connect;
    }

    private boolean isInputMsgError(Yangzhou yangzhou) {

        Pattern pattern = Pattern.compile("[0-9]{9}");
        Matcher isNum = pattern.matcher(yangzhou.getScode());
        if (!isNum.matches()) {
            return false;
        }

        pattern = Pattern.compile("[0-9]{8}");
        isNum = pattern.matcher(yangzhou.getDate());
        if (!isNum.matches()) {
            return false;
        }

        pattern = Pattern.compile("[0-9]{12}");
        isNum = pattern.matcher(yangzhou.getVal());
        if (!isNum.matches()) {
            return false;
        }

        return true;
    }

    void updateSelectMsg(String msg) {
        regularSelectMsg.setText(msg);
    }
}
